<?php
/**
 * Created by PhpStorm.
 * User: 陈艺赫
 * Date: 2018/5/4
 * Time: 11:17
 */

namespace app\user\model;

use think\Model;

class User extends Model
{
    public function parent()
    {
        return
            $this->belongsToMany('User', 'user_pid', 'user_pid', 'user_id');
    }

    /*
    * @param 用户id
    * @return array 当前用户所有权限
    * */
    public static function getUserFunctions($user_id)
    {
        $group_ids = Group::getGroupIds($user_id);
        $func_list = Group::where('id', 'in', $group_ids)->column('func_ids');
        $func_ids = explode(',', implode(',', $func_list));
        $func_ids = array_unique($func_ids);

        $funcs = Functions::where('id', 'in', $func_ids)->column('identify');
        return $funcs;
    }

    /*
    * @param 用户id
    * @return array 当前用户所有权限Info
    * */
    public static function getUserFunctionInfo($user_id)
    {
        $group_ids = Group::getGroupIds($user_id);
        $func_list = Group::where('id', 'in', $group_ids)->column('func_ids');
        $func_ids = explode(',', implode(',', $func_list));
        $func_ids = array_unique($func_ids);
        $funcs = Functions::where('id', 'in', $func_ids)->select();
        return $funcs;
    }

    /**
     * 生成盐值和密码
     * @param $password
     * @return array
     */
    public static function makePasswordAndSalt($password)
    {
        $salt = null;
        $salt = is_null($salt) ? random_string(5) : $salt;
        $password = $password . $salt . config('password');
        $password = md5(md5($password));
        return [
            'salt' => $salt,
            'password' => $password
        ];
    }

    /**
     * @param $username
     * @param $password
     * @param string $error 错误信息
     * @return bool
     */
    public static function userLogin($username, $password, $captcha, &$error = '')
    {
        $userInfo = self::get(['uname' => $username]);
        if (is_null($userInfo)) {
            $error = '用户不存在！';
            return false;
        }

        if ($userInfo['status'] == 0) {
            $error = '用户已被禁用！';
            return false;
        }

        if (!captcha_check($captcha)) {
            $error = '验证码错误';
            return false;
        };

        if (empty(Group::getGroup($userInfo['id']))){
            $error = '您所在的用户组已被关闭';
            return false;
        }
        // 校验密码
        $password = md5(md5($password . $userInfo['salt'] . config('password')));
        $hash = $userInfo['pwd'];
        if ($password !== $hash) {
            $error = '密码不正确！';
            return false;
        }

        //更新用户最后登录时间、ip
        $update_data = [
            'last_login_time' => date('Y-m-d H:i:s', time()),
            'last_login_ip' => get_client_ip(),
        ];

        self::update($update_data, ['uname' => $username]);
        self::setCookieAndSession($userInfo);
        return true;
    }

    /**
     * 登录成功后设置cookie、session
     * @param $userInfo
     */
    private static function setCookieAndSession($userInfo)
    {
        $powers = self::getUserFunctions($userInfo['id']);
        $menus = Menu::getUserMenus($userInfo['id']);
        $groups = Group::getGroup($userInfo['id']);
        //设置会话
        session('menus', $menus);
        session('powers', $powers);
        session('uname', $userInfo['uname']);
        session('id', $userInfo['id']);
        session('nickname', $userInfo['nickname']);
        session('group', $groups);
        session('last_login_time', $userInfo['last_login_time']);
        cookie('user_id', $userInfo['id'], 3600 * 24 * 1);
    }

    /**
     * 判断用户是否登录
     * @return bool
     */
    public static function isLogin()
    {
        $c_uid = cookie('user_id');
        $s_uid = session('id');
        $s_name = session('uname');

        return !is_null($c_uid) && !is_null($s_uid) && !is_null($s_name);
    }

    /**
     * @param $mca module:controller:action
     * @return bool
     */
    public static function hasPowerFunc($mca)
    {
        $powerFuncs = session('powers');
        return in_array($mca, $powerFuncs);
    }
}